package com.zdsoft.crm.controller.clue;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zdsoft.crm.entity.Clue;
import com.zdsoft.crm.entity.ClueSource;
import com.zdsoft.crm.entity.auth.SysUser;
import com.zdsoft.crm.service.auth.ISysUserService;
import com.zdsoft.crm.service.clue.IClueService;
import com.zdsoft.crm.util.DateUtil;
import com.zdsoft.crm.vo.AjaxVo;
import com.zdsoft.crm.vo.PageVo;
import com.zdsoft.crm.vo.clue.ClueUpdateVo;
import com.zdsoft.crm.vo.clue.ClueVo;

@Controller
@RequestMapping("/clue")
public class ClueController {

	@Autowired
	IClueService clueService;

	@Autowired
	ISysUserService iSysUserService;

	@Autowired
	HttpSession session;

	@GetMapping("/list")
	public ModelAndView clue(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			@RequestParam(name = "CriteriaType", defaultValue = "-1") String CriteriaType,
			@RequestParam(name = "content", defaultValue = "") String content) throws UnsupportedEncodingException {
		if(CriteriaType.equals("-1")){
			content="";
		}
		content = new String(content.getBytes("ISO8859-1"), "UTF-8");
		PageVo list = clueService.pageListWhere(pageNum, pageSize,CriteriaType,content);
		ModelAndView mav=new ModelAndView("/clue/list.html", "list", list);
		mav.addObject("CriteriaType", CriteriaType);
		mav.addObject("content", content);
		return mav;
	}

	@GetMapping("/getInfo")
	public ModelAndView getInfo(String id) {
		ModelAndView mav = new ModelAndView("/clue/info.html");
		Clue clue=clueService.getClueInfo(id);
		mav.addObject("clue", clue);
		String chargeUserId=clue.getCharge_user_id();
		if(!StringUtils.isEmpty(chargeUserId)){
			mav.addObject("charge", clueService.getUserName(chargeUserId));//负责人
		}else{
			mav.addObject("charge", "无");//负责人
		}
		String createUserId=clue.getCreate_user_id();
		if(!StringUtils.isEmpty(createUserId)){
			mav.addObject("create", clueService.getUserName(createUserId));//创建人
		}else{
			mav.addObject("create", "无");//创建人
		}
		mav.addObject("remark", new String(clue.getRemark()));//备注
		

		return mav;
	}

	@GetMapping("/")
	public ModelAndView saveUI() throws ClientProtocolException, IOException {
		List<String> provinceList = new ArrayList<>();
		// 获取httpClient
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		// 创建一个GET请求
		HttpGet httpget = new HttpGet(
				"http://restapi.amap.com/v3/config/district?key=9c161363abdaf80db6c56fa8f4472bf4");
		// 执行GET请求
		HttpResponse response = httpclient.execute(httpget);
		// if(response.getEntity().getContent())
		// 把inputstream 转换为字符串 ---- json对象
		String content = IOUtils.toString(response.getEntity().getContent(), "utf-8");
		// 把字符串转换为json对象
		JSONObject object = JSON.parseObject(content);
		// 解析下一级数据
		JSONArray array1 = object.getJSONArray("districts");
		JSONArray array2 = array1.getJSONObject(0).getJSONArray("districts");
		// System.out.println(array2.getJSONObject(0).getString("name"));

		// 循环
		Iterator<Object> iterator = array2.iterator();
		while (iterator.hasNext()) {
			JSONObject item = (JSONObject) iterator.next();
			provinceList.add(item.getString("name"));
		}
		ModelAndView mav = new ModelAndView("clue/save.html");
		mav.addObject("provinceList", provinceList);
		mav.addObject("source", clueService.getClueSourceAll());
		return mav;
	}

	/**
	 * TODO ajax get 中文参数 乱码
	 * 
	 * @param name
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@PostMapping("/data_ajax")
	@ResponseBody
	public List<String> data_ajax(String name) throws ClientProtocolException, IOException {
		List<String> dataList = new ArrayList<>();
		// 获取httpClient
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		// 创建一个GET请求
		HttpGet httpget = new HttpGet(
				"http://restapi.amap.com/v3/config/district?key=9c161363abdaf80db6c56fa8f4472bf4&keywords=" + name);
		// 执行GET请求
		HttpResponse response = httpclient.execute(httpget);
		// if(response.getEntity().getContent())
		// 把inputstream 转换为字符串 ---- json对象
		String content = IOUtils.toString(response.getEntity().getContent(), "utf-8");
		// 把字符串转换为json对象
		JSONObject object = JSON.parseObject(content);
		// 解析下一级数据
		JSONArray array1 = object.getJSONArray("districts");
		JSONArray array2 = array1.getJSONObject(0).getJSONArray("districts");
		// System.out.println(array2.getJSONObject(0).getString("name"));

		// 循环
		Iterator<Object> iterator = array2.iterator();
		while (iterator.hasNext()) {
			JSONObject item = (JSONObject) iterator.next();
			dataList.add(item.getString("name"));
		}
		return dataList;
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	@ResponseBody
	public AjaxVo delete(@PathVariable("id") String id) {
		clueService.delete(id);
		return new AjaxVo().setErrorMsg("0");
	}

	/**
	 * 编辑
	 * 
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	@GetMapping("/{id}")
	public ModelAndView updateUI(@PathVariable("id") String id) throws ClientProtocolException, IOException {

		ModelAndView mav = new ModelAndView("/clue/update.html");

		List<String> provinceList = new ArrayList<>();
		// 获取httpClient
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		// 创建一个GET请求
		HttpGet httpget = new HttpGet(
				"http://restapi.amap.com/v3/config/district?key=9c161363abdaf80db6c56fa8f4472bf4");
		// 执行GET请求
		HttpResponse response = httpclient.execute(httpget);
		// if(response.getEntity().getContent())
		// 把inputstream 转换为字符串 ---- json对象
		String content = IOUtils.toString(response.getEntity().getContent(), "utf-8");
		// 把字符串转换为json对象
		JSONObject object = JSON.parseObject(content);
		// 解析下一级数据
		JSONArray array1 = object.getJSONArray("districts");
		JSONArray array2 = array1.getJSONObject(0).getJSONArray("districts");
		// System.out.println(array2.getJSONObject(0).getString("name"));

		// 循环
		Iterator<Object> iterator = array2.iterator();
		while (iterator.hasNext()) {
			JSONObject item = (JSONObject) iterator.next();
			provinceList.add(item.getString("name"));
		}

		Clue clue = clueService.getClueInfo(id);// 根据id获取对象
		List<ClueSource> sourceList = clueService.getClueSourceAll();// 获取所有线索来源
		
		String chargeUserId=clue.getCharge_user_id();
		String createUserId=clue.getCreate_user_id();
		String chargeUser ="";
		String createUser ="";
		if(!StringUtils.isEmpty(chargeUserId)){
			chargeUser = clueService.getUserName(chargeUserId);// 获取负责人名字
		}
		if(!StringUtils.isEmpty(createUserId)){
			createUser = clueService.getUserName(createUserId);// 获取创建人名字
		}
		String[] address = clue.getAddress_info().split(",");
		String state = address[0];// 省份
		String city = address[1];// 城市
		String area = address[2];// 地区

		String street = "";
		if (address.length == 4) {
			street = address[3];// 街道
		}

		mav.addObject("clue", clue);
		mav.addObject("sourceList", sourceList);
		mav.addObject("chargeUser", chargeUser);
		mav.addObject("createUser", createUser);
		mav.addObject("state", state);
		mav.addObject("city", city);
		mav.addObject("area", area);
		mav.addObject("street", street);
		mav.addObject("provinceList", provinceList);
		mav.addObject("id", id);
		mav.addObject("remark_str", new String(clue.getRemark()));

		return mav;
	}

	@PostMapping("/{id}")
	public String update(@PathVariable("id") String id, ClueUpdateVo vo) {

		Clue clue = new Clue();
		clue.setId(id);// 设置修改的id
		
		String createUser=vo.getCreateUser();
		String chargeUser=vo.getChargeUser();
		String createUserId ="";
		String chargeUserId ="";
		if(!StringUtils.isEmpty(createUser)){
			createUserId = clueService.getUserId(createUser);// 获取创建人名字
		}
		if(!StringUtils.isEmpty(chargeUser)){
			chargeUserId = clueService.getUserId(chargeUser);// 获取负责人名字
		}
		
		clue.setCreate_user_id(createUserId);// 设置创建人id
		clue.setCharge_user_id(chargeUserId);// 设置负责人id
		clue.setCompany_name(vo.getCompany_name());// 设置公司名
		clue.setClue_source_id(vo.getClue_source_id());// 设置来源id
		clue.setContact_name(vo.getContact_name());// 设置联系人姓名
		clue.setJob(vo.getJob());// 设置职位
		clue.setSex(vo.getSex());// 设置尊称
		clue.setPhone(vo.getPhone());// 设置手机号
		clue.setEmail(vo.getEmail());// 设置邮箱
		clue.setAddress_info(vo.getState() + "," + vo.getCity() + "," + vo.getArea() + "," + vo.getStreet());// 设置地址拼接
		clue.setNext_contact_time(DateUtil.toDate(vo.getNext_contact_time()));// 设置下次联系时间
		clue.setNext_contact_info(vo.getNext_contact_info());// 设置下次联系内容
		clue.setRemark(vo.getRemark().getBytes());// 设置备注

		clueService.update(clue);


		return "redirect:/clue/list";

	}

	@PostMapping
	@ResponseBody
	public boolean savea(ClueVo clueVo) {
		Clue c = new Clue();
		c.setCompany_name(clueVo.getCompany_name());// 公司名称
		c.setContact_name(clueVo.getContact_name());// 联系人姓名
		c.setJob(clueVo.getJob());// 职位
		c.setSex(clueVo.getSex());// 尊称 0 女士 1先生
		c.setPhone(clueVo.getPhone());// 手机号
		c.setEmail(clueVo.getEmail());// 邮箱
		c.setNext_contact_info(clueVo.getNext_contact_info());// 下次联系内容
		c.setNext_contact_time(DateUtil.toDate(clueVo.getNext_contact_time()));// 下次联系时间
		c.setRemark(clueVo.getRemark().getBytes());// 备注

		SysUser usera = iSysUserService.findByUserName(clueVo.getUsername());
		if (usera != null) {
			String charge_user_id = usera.getId();
			c.setCharge_user_id(charge_user_id);// 线索负责人
			c.setAddress_info(
					clueVo.getProvince() + "," + clueVo.getCity() + "," + clueVo.getArea() + "," + clueVo.getAreac());// 地址信息,建议用,号分割
			SysUser user = (SysUser) session.getAttribute("user");
			String create_user_id = user.getId();
			c.setCreate_user_id(create_user_id);// 创建人
			c.setClue_source_id(clueVo.getClue_source_id());// 客户来源
			int i = clueService.save(c);
			System.out.println(i);
			return true;

		}
		return false;

	}
	
	@DeleteMapping("/delete")
	@ResponseBody // ajax提交时必须需要加的注解
	public void deleteAll(@RequestBody String idsStr) {
		System.out.println(idsStr);
		String[] list=idsStr.split(",");
		if(list.length!=0){
			for (String string : list) {
				clueService.delete(string);
			}
		}
	}
	
	/**
	 * 线索池
	 * @param clueVo
	 * @return
	 */
	@PostMapping("/pool")
	@ResponseBody // ajax提交时必须需要加的注解
	public boolean pool(ClueVo clueVo) {
		Clue c = new Clue();
		c.setCompany_name(clueVo.getCompany_name());// 公司名称
		c.setContact_name(clueVo.getContact_name());// 联系人姓名
		c.setJob(clueVo.getJob());// 职位
		c.setSex(clueVo.getSex());// 尊称 0 女士 1先生
		Integer phone=clueVo.getPhone();
		if(phone==null||phone.equals("")){
			c.setPhone(0);// 手机号
		}else{
			c.setPhone(phone);// 手机号
		}
		c.setEmail(clueVo.getEmail());// 邮箱
		c.setNext_contact_info(clueVo.getNext_contact_info());// 下次联系内容
		c.setNext_contact_time(DateUtil.toDate(clueVo.getNext_contact_time()));// 下次联系时间
		c.setRemark(clueVo.getRemark().getBytes());// 备注
		c.setAddress_info(
				clueVo.getProvince() + "," + clueVo.getCity() + "," + clueVo.getArea() + "," + clueVo.getAreac());// 地址信息,建议用,号分割
		SysUser user = (SysUser) session.getAttribute("user");
		String create_user_id = user.getId();
		c.setCreate_user_id(create_user_id);// 创建人
		c.setClue_source_id(clueVo.getClue_source_id());// 客户来源
		
		c.setCharge_user_id("");// 线索负责人
		int row=clueService.save(c);
		if(row!=0){
			return true;
		}
		return false;
	}
	
	/**
	 * 线索池
	 * @param clueVo
	 * @return
	 */
	@PostMapping("/updatePool/{id}")
	@ResponseBody // ajax提交时必须需要加的注解
	public boolean updatePool(@PathVariable("id") String id,ClueUpdateVo vo) {
		Clue clue = new Clue();
		clue.setId(id);// 设置修改的id
		
		String createUser=vo.getCreateUser();
		String createUserId ="";
		if(!StringUtils.isEmpty(createUser)){
			createUserId = clueService.getUserId(createUser);// 获取创建人id
		}
		/*if(!StringUtils.isEmpty(chargeUser)){
			chargeUserId = clueService.getUserId(chargeUser);// 获取负责人id
		}*/
		
		clue.setCreate_user_id(createUserId);// 设置创建人id
		clue.setCharge_user_id("");// 设置负责人id(设置为空)
		clue.setCompany_name(vo.getCompany_name());// 设置公司名
		clue.setClue_source_id(vo.getClue_source_id());// 设置来源id
		clue.setContact_name(vo.getContact_name());// 设置联系人姓名
		clue.setJob(vo.getJob());// 设置职位
		clue.setSex(vo.getSex());// 设置尊称
		clue.setPhone(vo.getPhone());// 设置手机号
		clue.setEmail(vo.getEmail());// 设置邮箱
		clue.setAddress_info(vo.getState() + "," + vo.getCity() + "," + vo.getArea() + "," + vo.getStreet());// 设置地址拼接
		clue.setNext_contact_time(DateUtil.toDate(vo.getNext_contact_time()));// 设置下次联系时间
		clue.setNext_contact_info(vo.getNext_contact_info());// 设置下次联系内容
		clue.setRemark(vo.getRemark().getBytes());// 设置备注

		int row=clueService.update(clue);
		if(row!=0){
			return true;
		}
		return false;

	}
	

}
